package com.xhwl.logistics.service.logistics.impl;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.logistics.converter.mapstruct.logistics.CrenelGroupConverter;
import com.xhwl.logistics.dao.mapper.logistics.CrenelGroupMapper;
import com.xhwl.logistics.entity.logistics.CrenelGroup;
import com.xhwl.logistics.entity.logistics.Device;
import com.xhwl.logistics.logistics.request.CrenelGroupParam;
import com.xhwl.logistics.query.CrenelGroupQuery;
import com.xhwl.logistics.query.iot.IotDeviceQuery;
import com.xhwl.logistics.service.cent.iot.ICentDeviceCoreService;
import com.xhwl.logistics.service.logistics.CrenelGroupService;
import com.xhwl.logistics.util.PageResult;
import com.xhwl.logistics.util.PageResultUtils;
import com.xhwl.logistics.vo.logistics.CrenelGroupVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 垛口分组管理服务类
 */
@Slf4j
@Service(value = "crenelGroupService")
public class CrenelGroupServiceImpl extends ServiceImpl<CrenelGroupMapper, CrenelGroup> implements CrenelGroupService {

    @Autowired
    private CrenelGroupMapper crenelGroupMapper;

    @Autowired
    private ICentDeviceCoreService deviceCoreService;

    @Override
    public PageResult<CrenelGroupVO> pageCrenelGroup(CrenelGroupQuery query) {
        log.info("pageCrenelGroup() called with parameters => 【query = {}】",query);
        //从自己业务库获取的数据信息
        Page<CrenelGroup> crenelGroupPage = crenelGroupMapper.pageCrenelGroup(query,PageResultUtils.getMyBatisPlusPage(query));
        List<CrenelGroup> records = Optional.ofNullable(crenelGroupPage.getRecords()).orElse(Collections.emptyList());
        if (records.size()>0) {
            List<CrenelGroupVO> crenelGroupVOList = CrenelGroupConverter.INSTANCE.toVoConvertList(records);
            for (CrenelGroupVO groupVO : crenelGroupVOList) {
                //获取每一个分组关联的设备信息列表数据
                String monitorIds = groupVO.getRelationMonitorId();
                String deviceName = groupVO.getDeviceName();
                String[] idArray = monitorIds.split(",");
                String[] deviceNameArray = deviceName.split(",");
                List<Device>result=new ArrayList<>();
                for (int i = 0; i < idArray.length; i++) {
                    Device device = new Device();
                    device.setId(Integer.parseInt(idArray[i]));
                    device.setDeviceName(deviceNameArray[i]);
                    result.add(device);
                }
                groupVO.setDeviceList(result);
            }
            return PageResultUtils.getPageResult(crenelGroupPage, crenelGroupVOList);
        }
        return PageResultUtils.getPageResult(crenelGroupPage,Collections.emptyList());
    }

    /**
     * 保存垛口分组管理
     * @param params
     * @return
     */
    @Override
    public ResultJson saveOrUpdateCrenelGroup(CrenelGroupParam params) {
        log.info("saveOrUpdateCrenelGroup() called with parameters => 【params = {}】",params);
        try {
            if (ObjectUtil.isNull(Optional.ofNullable(params).map(x -> x.getCreateDate()).orElse(null))) {
                params.setCreateDate(new Date());
            }
            CrenelGroup crenelGroup = new CrenelGroup();
            BeanUtils.copyProperties(params,crenelGroup);
            List<Device> devices = Optional.ofNullable(params).map(x -> x.getDeviceList()).orElse(Collections.emptyList());
            //传递过来的设备名称大于0
            if (devices.size()>0) {
                crenelGroup.setMonitorCount(devices.size());
                crenelGroup.setRelationDeviceCode(devices.stream().map(x->x.getDeviceCode()).collect(Collectors.joining(",")));
                crenelGroup.setDeviceName(devices.stream().map(x->x.getDeviceName()).collect(Collectors.joining(",")));
                crenelGroup.setRelationMonitorId(
                        devices.stream().map(x->String.valueOf(x.getId())).collect(Collectors.joining(","))
                );
            }
            this.saveOrUpdateBatch(Arrays.asList(crenelGroup));
        } catch (BeansException e) {
            e.printStackTrace();
            return ResultJson.fail(e.getMessage());
        }
        return ResultJson.success();
    }

    /**
     * 查询获取垛口分组管理中的详情或者列表数据
     * @param query
     * @return
     */
    @Override
    public ResultJson<CrenelGroupVO> queryCrenelGroupList(CrenelGroupQuery query) {
        log.info("queryCrenelGroupList() called with parameters => 【query = {}】",query);
        List<CrenelGroup> list =Optional.ofNullable(this.crenelGroupMapper.queryCrenelGroupList(query)).orElse(Collections.emptyList());
        if (list.size()>0) {
            List<CrenelGroupVO> crenelGroupVOList = CrenelGroupConverter.INSTANCE.toVoConvertList(list);
            for (CrenelGroupVO obj : crenelGroupVOList) {
                //每一个分组关联的设备id，可以是多个
                String deviceIds =Optional.ofNullable(obj.getRelationMonitorId()).orElse(null);
                String deviceNames = Optional.ofNullable(obj).map(x -> x.getDeviceName()).orElse(null);
                if (ObjectUtil.isNotNull(deviceIds)) {
                    String[] deviceKey = deviceIds.split(",");
                    String[] deviceNameArray = deviceNames.split(",");
                    List<Device>deviceList=new ArrayList<>();
                    for (int i = 0; i < deviceKey.length; i++) {
                        Device device = new Device();
                        device.setId(Integer.parseInt(deviceKey[i]));
                        device.setDeviceName(deviceNameArray[i]);
                        deviceList.add(device);
                    }
                    obj.setDeviceList(deviceList);
                }
            }
            return ResultJson.success(crenelGroupVOList);
        }
        return ResultJson.success(Collections.emptyList());
    }

    @Override
    public ResultJson deleteCrenelGroupService(String ids) {
        try {
            log.info("crenelGroupService() called with parameters => 【ids = {}】",ids);
            String[] split = ids.split(",");
            this.crenelGroupMapper.deleteBatchIds(Arrays.asList(split));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultJson.fail(CodeEnum.BUSINESS_EXCEPTION.getDescription());
        }
        return ResultJson.success();
    }


    @Override
    public ResultJson queryDeviceByGroupIds(String groupIds) {
        log.info("queryDeviceByGroupIds() called with parameters => 【groupIds = {}】",groupIds);
        CrenelGroupQuery crenelGroupQuery = new CrenelGroupQuery();
        crenelGroupQuery.setId(groupIds);
        List<CrenelGroup> crenelGroups =Optional.ofNullable(this.crenelGroupMapper.queryCrenelGroupList(crenelGroupQuery)).orElse(Collections.emptyList());
        if (crenelGroups.size()>0) {
            List<Object>list=new ArrayList<>();
            String codeList=null;
            for (int i = 0; i < crenelGroups.size(); i++) {
                CrenelGroup crenelGroup = crenelGroups.get(i);
                //获取关联的设备id
                codeList = Optional.ofNullable(crenelGroup.getRelationDeviceCode()).orElse(null);
            }
            if (codeList.split(",").length>0) {
                for (String key : codeList.split(",")) {
                    IotDeviceQuery iotDeviceQuery = new IotDeviceQuery();
                    iotDeviceQuery.setDeviceCode(key);
                    //通过iot设备中台获取设备信息
                    Object o = Optional.ofNullable(deviceCoreService.listDevice(iotDeviceQuery)).map(x -> x.getResult()).orElse(null);
                    Object records = ((JSONObject) o).get("records");
                    list.add(((JSONArray) records).get(0));
                }
            }
            return ResultJson.success(list);
        }
        return null;
    }
}
